<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;

class Article extends AdminBase
{
    public function index()
    {
        //构造搜索表单HTML渲染内容 ------ 开始
        $assign['doc_name'] = $this->request->param('doc_name');
        $assign['title'] = $this->request->param('title');
        $assign['category_id'] = $this->request->param('category_id');
        //获取所有一级分类
        $assign['top_categories'] = model('Category')->where([['pid','=',0]])->select()->toArray();
        if($assign['category_id'])
        {
            //获取选中的一级分类信息
            $assign['selected_top_category'] = model('Category')->where([['id','=',$assign['category_id']]])->find();
        }
        else
        {
            $assign['selected_top_category'] = [];
        }
        //构造搜索表单HTML渲染内容 ------ 结束

        //查询列表数据 ------ 开始
        //构造查询条件
        $where = [];
        $assign['title'] && $where[] = ['title','like', '%'.$assign['title'].'%'];
        $assign['category_id'] && $where[] = ['category_id','=', $assign['category_id']];
        if ($assign['doc_name']) {
            $doc_ids = model('Doc')->where([['name','like','%'.$assign['doc_name'].'%']])->field('id')->select()->toArray();
            if ($doc_ids) {
                $where[] = ['doc_id','in',array_column($doc_ids,'id')];
            }
        }

        //执行列表sql查询
        $assign['list'] = model('Article')->where($where)->order('id DESC')->paginate();
        $assign['page'] = $assign['list']->render();
        $assign['total'] = $assign['list']->total();
        //查询列表数据 ------ 结束
        $this->assign($assign);
        return $this->fetch();
    }

    //添加文章
    public function add()
    {
        if( $this->request->isPost() )
        {
            $validate = new \app\admin\validate\Article\Add;
            $param = $this->request->param();

            $data['doc_id'] = intval( $param['doc_id'] );
            if( $data['doc_id'] )
            {
                $param['category_id'] = model('Doc')->getFieldById($data['doc_id'],'category_id');
            }
            if (!$validate->check($param))
            {
                return $this->error($validate->getError());
            }
            else
            {
                $data['title'] = $param['title'];
                $data['category_id'] = intval( $param['category_id'] );
                $data['doc_id'] && $data['doc_catelog_id'] = ( isset( $param['doc_catelog_id'] ) && $param['doc_catelog_id'] > 0 ) ? $param['doc_catelog_id'] : $param['top_catelog_id'];
                ( intval( $param['sort'] ) > 0 ) && $data['sort'] = $param['sort'];
                $data['is_publish'] = ( isset( $param['is_publish'] ) && $param['is_publish'] > 0 ) ? intval( $param['is_publish'] ) : 0;
                $data['content'] = $param['editor-markdown-doc'];
                $data['create_time'] = time();
                $id = model('Article')->insertGetId($data);
                if( $id )
                {
                    //如果添加的是一篇单独的文章，不是一篇文档内的文章，往listing表增加关联数据
                    if( !$data['doc_id'] )
                    {
                        model('Listing')->insert(['rel_id'=>$id,'is_doc'=>0,'category_id'=>$data['category_id'],'is_publish'=>$data['is_publish']]);
                    }
                    return $this->redirect(url('/admin/article/'));
                }
                else
                {
                    return $this->error(model('Article')->getError());
                }
            }
        }
        else
        {
            $assign['doc_id'] = $this->request->param('doc_id');
            //获取所有一级分类
            $assign['top_categories'] = model('Category')->where("pid", 0)->select()->toArray();
            //获取所有顶级目录
            if( $assign['doc_id'] ){
                $assign['top_catelog'] = model('DocCatelog')->where([
                    ['doc_id','=',$assign['doc_id']],
                    ['pid','=',0]
                ])->select()->toArray();
            }
            $this->assign($assign);
            return $this->fetch();
        }
    }

    public function add_new()
    {
        if( $this->request->isPost() )
        {
            $validate = new \app\admin\validate\Article\Add;
            $param = $this->request->param();

            $data['doc_id'] = intval( $param['doc_id'] );
            if( $data['doc_id'] )
            {
                $param['category_id'] = model('Doc')->getFieldById($data['doc_id'],'category_id');
            }
            if (!$validate->check($param))
            {
                return $this->error($validate->getError());
            }
            else
            {
                $data['title'] = $param['title'];
                $data['category_id'] = intval( $param['category_id'] );
                ( intval( $param['sort'] ) > 0 ) && $data['sort'] = $param['sort'];
                $data['is_publish'] = ( isset( $param['is_publish'] ) && $param['is_publish'] > 0 ) ? intval( $param['is_publish'] ) : 0;
                $data['content'] = $param['editor-markdown-doc'];
                $data['create_time'] = time();
                $id = model('Article')->insertGetId($data);
                if( $id )
                {
                    //如果添加的是一篇单独的文章，不是一篇文档内的文章，往listing表增加关联数据
                    if( !$data['doc_id'] )
                    {
                        model('Listing')->insert(['rel_id'=>$id,'is_doc'=>0,'category_id'=>$data['category_id'],'is_publish'=>$data['is_publish']]);
                    }
                    return $this->redirect(url('/admin/article/'));
                }
                else
                {
                    return $this->error(model('Article')->getError());
                }
            }
        }
        else
        {
            $assign['doc_id'] = $this->request->param('doc_id');
            //获取所有一级分类
            $assign['top_categories'] = model('Category')->where("pid", 0)->select()->toArray();
            $this->assign($assign);
            return $this->fetch();
        }
    }

    public function edit()
    {
        $id = $this->request->param('id');
        if( $this->request->isPost() )
        {
            $validate = new \app\admin\validate\Article\Edit;
            $param = $this->request->param();
            if( $param['doc_id'] )
            {
                $param['category_id'] = model('Doc')->getFieldById($param['doc_id'],'category_id');
            }
            if (!$validate->check($param))
            {
                return $this->error($validate->getError());
            }
            else
            {
                $param['is_publish'] = isset( $param['is_publish'] ) ? $param['is_publish'] : 0;
                $data['id'] = $id;
                $data['title'] = $param['title'];
                $data['category_id'] = intval( $param['category_id'] );
                $data['doc_catelog_id'] = ( isset( $param['doc_catelog_id'] ) && $param['doc_catelog_id'] > 0 ) ? $param['doc_catelog_id'] :
                    (isset($param['top_catelog_id']) && $param['top_catelog_id'] > 0 ) ? $param['top_catelog_id'] : 0;
                ( intval( $param['sort'] ) > 0 ) && $data['sort'] = $param['sort'];
                $data['is_publish'] = $param['is_publish'];
                $data['content'] = $param['editor-markdown-doc'];
                $save_status = model('Article')->save($data, $id);
                if( $save_status !== false )
                {
                    if( $param['doc_id'] == 0 )
                    {
                        $save['category_id'] = $param['category_id'];
                        $save['is_publish'] = $param['is_publish'];
                        $where[] = ['rel_id','=',$id];
                        $where[] = ['is_doc','=',0];
                        model('Listing')->save($save,$where);
                    }
                    return $this->redirect(url('/admin/article/'));
                }
                else
                {
                    return $this->error(model('Article')->getError());
                }
            }
        }
        else
        {
            //获取信息
            $assign['info'] = model('Article')->find($id);
            //获取所有一级分类
            $assign['top_categories'] = model('Category')->where([['pid','=',0]])->select()->toArray();
            //获取选中的二级分类信息
            $assign['selected_sec_category'] = model('Category')->where([['id','=',$assign['info']['category_id']]])->find();
            //获取选中的一级分类信息
            $assign['selected_top_category'] = model('Category')->where([['id','=',$assign['selected_sec_category']['pid']]])->find();
            //获取所有二级分类
            $assign['sec_categories'] = model('Category')->where([['pid','=',$assign['selected_top_category']['id']]])->select()->toArray();
            //获取目录信息，必须是文档，才有目录信息
            if( $assign['info']['doc_id'] )
            {
                //获取所有的一级目录
                $assign['top_catelog'] = model('DocCatelog')->where([
                    ['doc_id','=',$assign['info']['doc_id']],
                    ['pid','=',0]
                ])->select()->toArray();
                //获取选中的目录信息
                $selected_catelog_info = model('DocCatelog')->where([['id','=',$assign['info']['doc_catelog_id']]])->find();
                if( $selected_catelog_info )
                {
                    //判断选中目录如果是二级目录
                    if( $selected_catelog_info['pid'] > 0 )
                    {
                        //获取选中的二级目录信息
                        $assign['selected_sec_catelog'] = $selected_catelog_info;
                        //获取选中的一级目录信息
                        $assign['selected_top_catelog'] = model('DocCatelog')->where([['id','=',$assign['selected_sec_catelog']['pid']]])->find();
                        //获取所有二级目录
                        $assign['sec_catelog'] = model('DocCatelog')->where([
                            ['doc_id','=',$assign['info']['doc_id']],
                            ['pid','=',$assign['selected_top_catelog']['id']]
                        ])->select()->toArray();
                    }
                    //如果选中的目录是一级目录
                    else
                    {
                        //获取选中的一级目录信息
                        $assign['selected_top_catelog'] = $selected_catelog_info;
                    }
                }
            }
            $this->assign($assign);
            return $this->fetch();
        }
    }

    public function edit_new()
    {
        $id = $this->request->param('id');
        if( $this->request->isPost() )
        {
            $validate = new \app\admin\validate\Article\Edit;
            $param = $this->request->param();
            if( $param['doc_id'] )
            {
                $param['category_id'] = model('Doc')->getFieldById($param['doc_id'],'category_id');
            }
            if (!$validate->check($param))
            {
                return $this->error($validate->getError());
            }
            else
            {
                $param['is_publish'] = isset( $param['is_publish'] ) ? $param['is_publish'] : 0;
                $data['id'] = $id;
                $data['title'] = $param['title'];
                $data['category_id'] = intval( $param['category_id'] );
                ( intval( $param['sort'] ) > 0 ) && $data['sort'] = $param['sort'];
                $data['is_publish'] = $param['is_publish'];
                $data['content'] = $param['editor-markdown-doc'];
                $save_status = model('Article')->save($data, $id);
                if( $save_status !== false )
                {
                    if( $param['doc_id'] == 0 )
                    {
                        $save['category_id'] = $param['category_id'];
                        $save['is_publish'] = $param['is_publish'];
                        $where[] = ['rel_id','=',$id];
                        $where[] = ['is_doc','=',0];
                        model('Listing')->save($save,$where);
                    }
                    return $this->redirect(url('/admin/article/'));
                }
                else
                {
                    return $this->error(model('Article')->getError());
                }
            }
        }
        else
        {
            //获取信息
            $assign['info'] = model('Article')->find($id);
            //获取所有一级分类
            $assign['top_categories'] = model('Category')->where([['pid','=',0]])->select()->toArray();
            $this->assign($assign);
            return $this->fetch();
        }
    }

    public function del()
    {
        $id = $this->request->param('id');
        $validate = new \app\admin\validate\Article\Del;
        if (!$validate->check(['id'=>$id]))
        {
            return $this->error($validate->getError());
        }
        else
        {
            $res = model('Article')->where('id', $id)->delete();
            if( $res !== false )
            {
                return $this->success('操作成功', url('/admin/article/'));
            }
            else
            {
                return $this->error(model('Article')->getError());
            }
        }
    }
}
